import { computed, ref } from "vue";
import {
  createDiscreteApi,
  ConfigProviderProps,
  darkTheme,
  lightTheme,
} from "naive-ui";
import { useAppStore } from "@/stores/app";

const themeRef = ref(false);
const configProviderPropsRef = computed<ConfigProviderProps>(() => ({
  theme: themeRef.value ? darkTheme : lightTheme,
}));

const { message, notification, dialog, loadingBar } = createDiscreteApi(
  ["message", "dialog", "notification", "loadingBar"],
  {
    configProviderProps: configProviderPropsRef,
  }
);

export enum MessageStyle {
  "none",
  "message",
  "notification",
  "dialog",
}

export type ZTipType = "default" | "error" | "info" | "success" | "warning";
function getZTipTitle(typ: ZTipType) {
  return {
    default: "通知",
    error: "错误",
    info: "消息",
    success: "成功",
    warning: "警告",
  }[typ];
}

const tipDuration = 5000;

/**
 * default tips
 */
function zTip(
  msg?: string | undefined,
  msgStyle: MessageStyle = MessageStyle.message,
  type: ZTipType = "default"
) {
  if (!msg) return;

  // TODO: more works about specified status, and i18n.
  const title = getZTipTitle(type);

  switch (msgStyle) {
    case MessageStyle.dialog: {
      dialog.create({
        type,
        title,
        content: msg,
        closable: true,
        positiveText: "确认",
      });
      break;
    }
    case MessageStyle.notification: {
      notification.create({
        type,
        title,
        content: msg,
        duration: tipDuration,
        closable: true,
      });
      break;
    }
    case MessageStyle.none: {
      break;
    }
    case MessageStyle.message:
    default: {
      message.create(msg, {
        type,
        duration: tipDuration,
        closable: true,
        keepAliveOnHover: true,
      });
      break;
    }
  }
}

export function useMessage() {
  const appStore = useAppStore();
  themeRef.value = appStore.darkTheme;

  return {
    zMessage: message,
    zNotification: notification,
    zDialog: dialog,
    zLoadingBar: loadingBar,
    zTip,
  };
}
